package com.naiterui.ehp.bs.b2c.order.service.impl.logistics;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.naiterui.ehp.bp.support.exception.JsonException;
import com.naiterui.ehp.bp.support.utils.JsonMapper;
import com.naiterui.ehp.bp.utils.encypt.MD5;
import com.naiterui.ehp.bp.utils.net.RestHttpUtil;
import com.naiterui.ehp.bs.b2c.order.bo.LogisticsInfoBO;
import com.naiterui.ehp.bs.b2c.order.bo.LogisticsTraceLogBO;
import com.naiterui.ehp.bs.b2c.order.vo.logistics.BaseResponse;
import com.naiterui.ehp.bs.b2c.order.vo.logistics.kuaidi100.request.Kd100TraceQueryRequest;
import com.naiterui.ehp.bs.b2c.order.vo.logistics.kuaidi100.response.Kd100TraceQueryResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * <pre>
 *      快递100
 * </pre>
 *
 * @author 王泽浩
 * @date 2019/10/11 2:16 下午
 * @since 1.0.0
 */
@Slf4j
@Service("kudi100")
public class Kudi100LogisticsTraceServiceImpl extends AbstractLogisticsTraceService<Kd100TraceQueryRequest> {

    @Value("${kuaidi100.key}")
    private String key;
    @Value("${kuaidi100.customer}")
    private String customer;

    @Override
    protected <E extends BaseResponse> E execute(Kd100TraceQueryRequest kd100TraceQueryRequest,
                                                 ParameterizedTypeReference<E> responseTypeReference) {

        String bizData = JsonMapper.toJson(kd100TraceQueryRequest);
        Map<String, String> params = Maps.newHashMap();
        params.put("customer", this.customer);
        params.put("param", bizData);
        params.put("sign", MD5.md5(bizData + this.key + this.customer).toUpperCase());
        ResponseEntity<String> responseEntity = RestHttpUtil.post()
                                                            .url(kd100TraceQueryRequest.getServiceUrl())
                                                            .paramMap(params)
                                                            .execute(new ParameterizedTypeReference<String>() {
                                                            });
        return JsonMapper.toObject(responseEntity.getBody(), responseTypeReference);
    }

    @Override
    public LogisticsInfoBO getTrace(String deliveryId, String companyCode, String phone) {
        log.info("调用快递100获取快递 请求参数：deliveryId = {}, companyCode = {} phone = {}", deliveryId, companyCode, phone);
        LogisticsInfoBO logisticsInfoBO = new LogisticsInfoBO();
        logisticsInfoBO.setDeliveryId(deliveryId);
        try {
            Kd100TraceQueryRequest kd100TraceQueryRequest = new Kd100TraceQueryRequest();
            kd100TraceQueryRequest.setCom(companyCode);
            kd100TraceQueryRequest.setNum(deliveryId);
            kd100TraceQueryRequest.setPhone(phone);
            Kd100TraceQueryResponse response = this.execute(kd100TraceQueryRequest, new ParameterizedTypeReference<Kd100TraceQueryResponse>() {
            });
            log.debug("返回结果 {}", response);
            Integer state = response.getState();
            if (state != null) {
                if (state == 3) {
                    logisticsInfoBO.setStatus(LogisticsInfoBO.STATUS_RECEIVED);
                } else if (state == 0 || state == 5) {
                    logisticsInfoBO.setStatus(LogisticsInfoBO.STATUS_ONWAY);
                } else if (state == 1) {
                    logisticsInfoBO.setStatus(LogisticsInfoBO.STATUS_PICKUP);
                } else if (state == 6) {
                    logisticsInfoBO.setStatus(LogisticsInfoBO.STATUS_REJECT);
                }
                List<LogisticsTraceLogBO> traceLogs = response.getData().stream()
                                                              .map(logs -> LogisticsTraceLogBO.builder()
                                                                                              .time(logs.getTime())
                                                                                              .content(logs.getContext())
                                                                                              .build())
                                                              .collect(Collectors.toList());
                logisticsInfoBO.setTraceLogs(traceLogs);
            } else {
                logisticsInfoBO.setStatus(LogisticsInfoBO.STATUS_NONE);
            }
        } catch (JsonException e) {
            log.error("json转换失败", e);
            logisticsInfoBO.setStatus(LogisticsInfoBO.STATUS_NONE);
        }
        return logisticsInfoBO;
    }
}
